<template>
  <div class="article-detail-container" v-loading="loading">
    <el-card v-if="article">
      <template #header>
        <h1>{{ article.title }}</h1>
        <div class="article-meta">
          <span>作者: {{ article.author?.username }}</span>
          <span>发布于: {{ new Date(article.createdAt).toLocaleString() }}</span>
          <span v-if="article.updatedAt !== article.createdAt">最后更新于: {{ new Date(article.updatedAt).toLocaleString() }}</span>
        </div>
      </template>
      <div class="article-content" v-html="article.content"></div>
      <div class="actions mt-4" v-if="isAuthenticated && canEditOrDelete(article.author.id)">
         <el-button type="primary" @click="editArticle">编辑</el-button>
         <el-popconfirm title="确定删除这篇文章吗?" @confirm="deleteArticleHandler">
            <template #reference>
                <el-button type="danger">删除</el-button>
            </template>
         </el-popconfirm>
      </div>
      <div class="like-section" style="margin: 20px 0; display: flex; align-items: center;">
        <el-button type="success" @click="likeArticle" :disabled="likeLoading">
          <span v-if="likedByCurrentUser">👎 取消点赞</span>
          <span v-else>👍 点赞</span>
          {{ article.likeCount || 0 }}
        </el-button>
        <div class="like-avatars" style="display: flex; align-items: center; margin-left: 10px;">
          <el-avatar
            v-for="user in likeUsers"
            :key="user.id"
            :src="user.avatar"
            :size="28"
            :title="user.username"
            style="margin-right: -8px; border: 2px solid #fff; background: #eee;"
          >
            {{ user.username ? user.username.charAt(0).toUpperCase() : '' }}
          </el-avatar>
        </div>
      </div>
    </el-card>
    <el-empty description="文章未找到" v-else-if="!loading && !article"></el-empty>
    
    <!-- 评论区 -->
    <comment-section v-if="articleId && !loading" :article-id="articleId"></comment-section>

  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import CommentSection from '../components/CommentSection.vue'; // 导入评论组件

export default {
  name: 'ArticleDetail',
  components: { // 注册评论组件
    CommentSection
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const article = ref(null)
    const loading = ref(true)
    const likeLoading = ref(false)
    const likedByCurrentUser = ref(false)
    const likeUsers = ref([])

    const articleId = computed(() => route.params.id)
    const isAuthenticated = computed(() => !!localStorage.getItem('token'))
    const currentUser = computed(() => JSON.parse(localStorage.getItem('user') || '{}'))

    const fetchLikeUsers = async () => {
      try {
        const res = await axios.get(`/api/articles/${articleId.value}/like-users`)
        likeUsers.value = res.data
      } catch (e) {
        likeUsers.value = []
      }
    }

    const fetchArticle = async () => {
      loading.value = true
      try {
        const response = await axios.get(`/api/articles/${articleId.value}`)
        article.value = response.data
        likedByCurrentUser.value = response.data.likedByCurrentUser
      } catch (error) {
        ElMessage.error('获取文章详情失败')
        console.error(error)
        if (error.response && error.response.status === 404) {
            article.value = null; // Explicitly set to null if not found
        }
      } finally {
        loading.value = false
      }
    }
    
    const canEditOrDelete = (authorId) => {
        if (!isAuthenticated.value) return false;
        // Add admin role check if you have roles
        return currentUser.value.userId === authorId;
    };

    const editArticle = () => {
        router.push(`/articles/edit/${articleId.value}`);
    };

    const deleteArticleHandler = async () => {
      try {
        await axios.delete(`/api/articles/${articleId.value}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        ElMessage.success('文章删除成功');
        router.push('/articles');
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '删除文章失败');
        console.error(error);
      }
    };

    const likeArticle = async () => {
      likeLoading.value = true
      try {
        const token = localStorage.getItem('token')
        const response = await axios.post(
          `/api/articles/${articleId.value}/like`,
          {},
          { headers: { Authorization: `Bearer ${token}` } }
        )
        likedByCurrentUser.value = response.data.liked
        if (likedByCurrentUser.value) {
          article.value.likeCount = (article.value.likeCount || 0) + 1
          ElMessage.success('点赞成功')
        } else {
          article.value.likeCount = (article.value.likeCount || 1) - 1
          ElMessage.success('已取消点赞')
        }
        await fetchLikeUsers()
      } catch (e) {
        ElMessage.error('操作失败')
      } finally {
        likeLoading.value = false
      }
    }

    onMounted(() => {
      fetchArticle()
      fetchLikeUsers()
    })

    return {
      article,
      loading,
      isAuthenticated,
      canEditOrDelete,
      editArticle,
      deleteArticleHandler,
      articleId,
      likeLoading,
      likeArticle,
      likedByCurrentUser,
      likeUsers,
      fetchLikeUsers
    }
  }
}
</script>

<style scoped>
.article-detail-container {
  padding: 20px;
}
.article-meta {
  font-size: 0.9em;
  color: #666;
}
.article-meta span {
  margin-right: 15px;
}
.article-content {
  margin-top: 20px;
  line-height: 1.8;
}
.mt-4 {
  margin-top: 20px;
}
</style> 